1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.io;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21 import static com.google.common.io.FileWriteMode.APPEND;
22
23 import com.google.common.annotations.Beta;
24 import com.google.common.base.Charsets;
25 import com.google.common.base.Joiner;
26 import com.google.common.base.Predicate;
27 import com.google.common.base.Splitter;
28 import com.google.common.collect.ImmutableSet;
29 import com.google.common.collect.Lists;
30 import com.google.common.collect.TreeTraverser;
31 import com.google.common.hash.HashCode;
32 import com.google.common.hash.HashFunction;
33
34 import java.io.BufferedReader;
35 import java.io.BufferedWriter;
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.FileNotFoundException;
39 import java.io.FileOutputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.InputStreamReader;
43 import java.io.OutputStream;
44 import java.io.OutputStreamWriter;
45 import java.io.RandomAccessFile;
46 import java.nio.MappedByteBuffer;
47 import java.nio.channels.FileChannel;
48 import java.nio.channels.FileChannel.MapMode;
49 import java.nio.charset.Charset;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.Collections;
53 import java.util.List;
54
55
56
57
58
59
60
61
62
63
64 @Beta
65 public final class Files {
66
67
68 private static final int TEMP_DIR_ATTEMPTS = 10000;
69
70 private Files() {}
71
72
73
74
75
76
77
78
79
80
81 public static BufferedReader newReader(File file, Charset charset)
82 throws FileNotFoundException {
83 checkNotNull(file);
84 checkNotNull(charset);
85 return new BufferedReader(
86 new InputStreamReader(new FileInputStream(file), charset));
87 }
88
89
90
91
92
93
94
95
96
97
98 public static BufferedWriter newWriter(File file, Charset charset)
99 throws FileNotFoundException {
100 checkNotNull(file);
101 checkNotNull(charset);
102 return new BufferedWriter(
103 new OutputStreamWriter(new FileOutputStream(file), charset));
104 }
105
106
107
108
109
110
111 public static ByteSource asByteSource(File file) {
112 return new FileByteSource(file);
113 }
114
115 private static final class FileByteSource extends ByteSource {
116
117 private final File file;
118
119 private FileByteSource(File file) {
120 this.file = checkNotNull(file);
121 }
122
123 @Override
124 public FileInputStream openStream() throws IOException {
125 return new FileInputStream(file);
126 }
127
128 @Override
129 public long size() throws IOException {
130 if (!file.isFile()) {
131 throw new FileNotFoundException(file.toString());
132 }
133 return file.length();
134 }
135
136 @Override
137 public byte[] read() throws IOException {
138 Closer closer = Closer.create();
139 try {
140 FileInputStream in = closer.register(openStream());
141 return readFile(in, in.getChannel().size());
142 } catch (Throwable e) {
143 throw closer.rethrow(e);
144 } finally {
145 closer.close();
146 }
147 }
148
149 @Override
150 public String toString() {
151 return "Files.asByteSource(" + file + ")";
152 }
153 }
154
155
156
157
158
159
160
161 static byte[] readFile(
162 InputStream in, long expectedSize) throws IOException {
163 if (expectedSize > Integer.MAX_VALUE) {
164 throw new OutOfMemoryError("file is too large to fit in a byte array: "
165 + expectedSize + " bytes");
166 }
167
168
169
170 return expectedSize == 0
171 ? ByteStreams.toByteArray(in)
172 : ByteStreams.toByteArray(in, (int) expectedSize);
173 }
174
175
176
177
178
179
180
181
182
183
184 public static ByteSink asByteSink(File file, FileWriteMode... modes) {
185 return new FileByteSink(file, modes);
186 }
187
188 private static final class FileByteSink extends ByteSink {
189
190 private final File file;
191 private final ImmutableSet<FileWriteMode> modes;
192
193 private FileByteSink(File file, FileWriteMode... modes) {
194 this.file = checkNotNull(file);
195 this.modes = ImmutableSet.copyOf(modes);
196 }
197
198 @Override
199 public FileOutputStream openStream() throws IOException {
200 return new FileOutputStream(file, modes.contains(APPEND));
201 }
202
203 @Override
204 public String toString() {
205 return "Files.asByteSink(" + file + ", " + modes + ")";
206 }
207 }
208
209
210
211
212
213
214
215 public static CharSource asCharSource(File file, Charset charset) {
216 return asByteSource(file).asCharSource(charset);
217 }
218
219
220
221
222
223
224
225
226
227
228
229 public static CharSink asCharSink(File file, Charset charset,
230 FileWriteMode... modes) {
231 return asByteSink(file, modes).asCharSink(charset);
232 }
233
234 private static FileWriteMode[] modes(boolean append) {
235 return append
236 ? new FileWriteMode[]{ FileWriteMode.APPEND }
237 : new FileWriteMode[0];
238 }
239
240
241
242
243
244
245
246
247
248
249 public static byte[] toByteArray(File file) throws IOException {
250 return asByteSource(file).read();
251 }
252
253
254
255
256
257
258
259
260
261
262
263 public static String toString(File file, Charset charset) throws IOException {
264 return asCharSource(file, charset).read();
265 }
266
267
268
269
270
271
272
273
274 public static void write(byte[] from, File to) throws IOException {
275 asByteSink(to).write(from);
276 }
277
278
279
280
281
282
283
284
285 public static void copy(File from, OutputStream to) throws IOException {
286 asByteSource(from).copyTo(to);
287 }
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302 public static void copy(File from, File to) throws IOException {
303 checkArgument(!from.equals(to),
304 "Source %s and destination %s must be different", from, to);
305 asByteSource(from).copyTo(asByteSink(to));
306 }
307
308
309
310
311
312
313
314
315
316
317
318 public static void write(CharSequence from, File to, Charset charset)
319 throws IOException {
320 asCharSink(to, charset).write(from);
321 }
322
323
324
325
326
327
328
329
330
331
332
333 public static void append(CharSequence from, File to, Charset charset)
334 throws IOException {
335 write(from, to, charset, true);
336 }
337
338
339
340
341
342
343
344
345
346
347
348
349 private static void write(CharSequence from, File to, Charset charset,
350 boolean append) throws IOException {
351 asCharSink(to, charset, modes(append)).write(from);
352 }
353
354
355
356
357
358
359
360
361
362
363
364 public static void copy(File from, Charset charset, Appendable to)
365 throws IOException {
366 asCharSource(from, charset).copyTo(to);
367 }
368
369
370
371
372
373
374 public static boolean equal(File file1, File file2) throws IOException {
375 checkNotNull(file1);
376 checkNotNull(file2);
377 if (file1 == file2 || file1.equals(file2)) {
378 return true;
379 }
380
381
382
383
384
385
386 long len1 = file1.length();
387 long len2 = file2.length();
388 if (len1 != 0 && len2 != 0 && len1 != len2) {
389 return false;
390 }
391 return asByteSource(file1).contentEquals(asByteSource(file2));
392 }
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413 public static File createTempDir() {
414 File baseDir = new File(System.getProperty("java.io.tmpdir"));
415 String baseName = System.currentTimeMillis() + "-";
416
417 for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
418 File tempDir = new File(baseDir, baseName + counter);
419 if (tempDir.mkdir()) {
420 return tempDir;
421 }
422 }
423 throw new IllegalStateException("Failed to create directory within "
424 + TEMP_DIR_ATTEMPTS + " attempts (tried "
425 + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
426 }
427
428
429
430
431
432
433
434
435 public static void touch(File file) throws IOException {
436 checkNotNull(file);
437 if (!file.createNewFile()
438 && !file.setLastModified(System.currentTimeMillis())) {
439 throw new IOException("Unable to update modification time of " + file);
440 }
441 }
442
443
444
445
446
447
448
449
450
451
452
453 public static void createParentDirs(File file) throws IOException {
454 checkNotNull(file);
455 File parent = file.getCanonicalFile().getParentFile();
456 if (parent == null) {
457
458
459
460
461
462
463
464 return;
465 }
466 parent.mkdirs();
467 if (!parent.isDirectory()) {
468 throw new IOException("Unable to create parent directories of " + file);
469 }
470 }
471
472
473
474
475
476
477
478
479
480
481
482
483 public static void move(File from, File to) throws IOException {
484 checkNotNull(from);
485 checkNotNull(to);
486 checkArgument(!from.equals(to),
487 "Source %s and destination %s must be different", from, to);
488
489 if (!from.renameTo(to)) {
490 copy(from, to);
491 if (!from.delete()) {
492 if (!to.delete()) {
493 throw new IOException("Unable to delete " + to);
494 }
495 throw new IOException("Unable to delete " + from);
496 }
497 }
498 }
499
500
501
502
503
504
505
506
507
508
509
510
511 public static String readFirstLine(File file, Charset charset)
512 throws IOException {
513 return asCharSource(file, charset).readFirstLine();
514 }
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531 public static List<String> readLines(File file, Charset charset)
532 throws IOException {
533
534
535 return readLines(file, charset, new LineProcessor<List<String>>() {
536 final List<String> result = Lists.newArrayList();
537
538 @Override
539 public boolean processLine(String line) {
540 result.add(line);
541 return true;
542 }
543
544 @Override
545 public List<String> getResult() {
546 return result;
547 }
548 });
549 }
550
551
552
553
554
555
556
557
558
559
560
561
562 public static <T> T readLines(File file, Charset charset,
563 LineProcessor<T> callback) throws IOException {
564 return asCharSource(file, charset).readLines(callback);
565 }
566
567
568
569
570
571
572
573
574
575
576
577
578 public static <T> T readBytes(File file, ByteProcessor<T> processor)
579 throws IOException {
580 return asByteSource(file).read(processor);
581 }
582
583
584
585
586
587
588
589
590
591
592 public static HashCode hash(File file, HashFunction hashFunction)
593 throws IOException {
594 return asByteSource(file).hash(hashFunction);
595 }
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613 public static MappedByteBuffer map(File file) throws IOException {
614 checkNotNull(file);
615 return map(file, MapMode.READ_ONLY);
616 }
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636 public static MappedByteBuffer map(File file, MapMode mode)
637 throws IOException {
638 checkNotNull(file);
639 checkNotNull(mode);
640 if (!file.exists()) {
641 throw new FileNotFoundException(file.toString());
642 }
643 return map(file, mode, file.length());
644 }
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667 public static MappedByteBuffer map(File file, MapMode mode, long size)
668 throws FileNotFoundException, IOException {
669 checkNotNull(file);
670 checkNotNull(mode);
671
672 Closer closer = Closer.create();
673 try {
674 RandomAccessFile raf = closer.register(
675 new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
676 return map(raf, mode, size);
677 } catch (Throwable e) {
678 throw closer.rethrow(e);
679 } finally {
680 closer.close();
681 }
682 }
683
684 private static MappedByteBuffer map(RandomAccessFile raf, MapMode mode,
685 long size) throws IOException {
686 Closer closer = Closer.create();
687 try {
688 FileChannel channel = closer.register(raf.getChannel());
689 return channel.map(mode, 0, size);
690 } catch (Throwable e) {
691 throw closer.rethrow(e);
692 } finally {
693 closer.close();
694 }
695 }
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718 public static String simplifyPath(String pathname) {
719 checkNotNull(pathname);
720 if (pathname.length() == 0) {
721 return ".";
722 }
723
724
725 Iterable<String> components =
726 Splitter.on('/').omitEmptyStrings().split(pathname);
727 List<String> path = new ArrayList<String>();
728
729
730 for (String component : components) {
731 if (component.equals(".")) {
732 continue;
733 } else if (component.equals("..")) {
734 if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
735 path.remove(path.size() - 1);
736 } else {
737 path.add("..");
738 }
739 } else {
740 path.add(component);
741 }
742 }
743
744
745 String result = Joiner.on('/').join(path);
746 if (pathname.charAt(0) == '/') {
747 result = "/" + result;
748 }
749
750 while (result.startsWith("/../")) {
751 result = result.substring(3);
752 }
753 if (result.equals("/..")) {
754 result = "/";
755 } else if ("".equals(result)) {
756 result = ".";
757 }
758
759 return result;
760 }
761
762
763
764
765
766
767
768
769 public static String getFileExtension(String fullName) {
770 checkNotNull(fullName);
771 String fileName = new File(fullName).getName();
772 int dotIndex = fileName.lastIndexOf('.');
773 return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
774 }
775
776
777
778
779
780
781
782
783
784
785
786 public static String getNameWithoutExtension(String file) {
787 checkNotNull(file);
788 String fileName = new File(file).getName();
789 int dotIndex = fileName.lastIndexOf('.');
790 return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
791 }
792
793
794
795
796
797
798
799
800
801
802
803 public static TreeTraverser<File> fileTreeTraverser() {
804 return FILE_TREE_TRAVERSER;
805 }
806
807 private static final TreeTraverser<File> FILE_TREE_TRAVERSER = new TreeTraverser<File>() {
808 @Override
809 public Iterable<File> children(File file) {
810
811 if (file.isDirectory()) {
812 File[] files = file.listFiles();
813 if (files != null) {
814 return Collections.unmodifiableList(Arrays.asList(files));
815 }
816 }
817
818 return Collections.emptyList();
819 }
820
821 @Override
822 public String toString() {
823 return "Files.fileTreeTraverser()";
824 }
825 };
826
827
828
829
830
831
832 public static Predicate<File> isDirectory() {
833 return FilePredicate.IS_DIRECTORY;
834 }
835
836
837
838
839
840
841 public static Predicate<File> isFile() {
842 return FilePredicate.IS_FILE;
843 }
844
845 private enum FilePredicate implements Predicate<File> {
846 IS_DIRECTORY {
847 @Override
848 public boolean apply(File file) {
849 return file.isDirectory();
850 }
851
852 @Override
853 public String toString() {
854 return "Files.isDirectory()";
855 }
856 },
857
858 IS_FILE {
859 @Override
860 public boolean apply(File file) {
861 return file.isFile();
862 }
863
864 @Override
865 public String toString() {
866 return "Files.isFile()";
867 }
868 };
869 }
870 }